﻿using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using YTCMS.Core.Redis;
using YTCMS.Services;
using System.Linq.Expressions;

namespace App.Common
{
    public class RedisFactory<T> : IRedisFactory<T> where T :class
    {
        public List<T> Get(string key)
        {
            using (var rc = RedisManager.GetClient())
            {
                if (rc.Get<List<T>>(key) != null)
                {
                    var pi = rc.Get<List<T>>(key);
                    return pi;
                }
                else
                {
                    return default(List<T>);
                }
            }
        }
        public bool Set(string key,Expression<Func<T,bool>> func)
        {
            IUnityContainer container = new UnityContainer();
            using (var rc = RedisManager.GetClient())
            {
                try
                {
                    string file = HttpContext.Current.Server.MapPath("~/config/Unity.config");
                    var fileMap = new ExeConfigurationFileMap() { ExeConfigFilename = file };
                    var config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
                    var configuration = (UnityConfigurationSection)config.GetSection(UnityConfigurationSection.SectionName);
                    configuration.Configure(container, "defaultContainer");
                    var elements = configuration.Containers;
                    var typeName = typeof(T).Name;
                    foreach (var item in elements)
                    {
                        var registration = item.Registrations;
                        if (registration.Count > 0)
                        {
                            var regist = registration.Where(s => s.Name.Equals(typeName));
                            if (regist != null)
                            {
                                var tname = regist.First().MapToName;
                                Type t = Type.GetType(tname);
                                var servier = (IBaseService<T>)container.Resolve(t);
                                var many = servier.GetAsyncMany(func).ToList();
                                return rc.Set<List<T>>(key, many);
                            }
                        }

                    }
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
            }
            return false;
        }

        public bool Set(string key, object obj)
        {
            using (var rc = RedisManager.GetClient())
            {
                return rc.Set(key, obj);
            }
        } 
    }
}